const multer = require('koa-multer')
const fs = require('fs')
const path = require('path')
const router = require('koa-router')()
router.prefix('/upload')

let storage  = multer.diskStorage({
  destination: function (req,file,cb) {
    let date = new Date()
    let year = date.getFullYear()
    let month = date.getMonth()+1
    let day = date.getDate()
    let dir = "./public/images/"+ year+month+day
    //判断目录是否存在
    if(!fs.existsSync(dir)){
      fs.mkdirSync(dir,{
        recursive: true,
      })
    }
    cb(null,dir)
  },
  filename: function(req,file,cb){
    //设置上传文件名称
    let filename = file.fieldname+Date.now()+path.extname(file.originalname);
    cb(null,filename)
  }
})
let upload = multer({ storage: storage });
//上传图片接口
router.post('/img',upload.single('file'),async ctx =>{
  let src = ctx.req.file.path
  src = ctx.origin +''+src.replace('public','').replace(/\\/g,'/')
  ctx.body = {
    data:src
  }
})


module.exports = router 